from django.http import JsonResponse, HttpResponse, Http404
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from django.conf import settings
from .models import KnowledgeBase, KnowledgeDetail
from .utils import get_knowledge_files_dir, generate_date_based_filename, get_file_info
import json
import os
import mimetypes
import urllib.parse
from datetime import datetime

# 确保知识库文件目录存在
KNOWLEDGE_FILES_DIR = get_knowledge_files_dir()

@csrf_exempt
@require_http_methods(["GET"])
def get_knowledge_list(request):
    """获取知识库列表"""
    try:
        # 获取筛选参数
        content_type = request.GET.get('type', '')
        category = request.GET.get('category', '')
        status = request.GET.get('status', '')
        keyword = request.GET.get('keyword', '')
        
        # 构建查询
        queryset = KnowledgeBase.objects.all()
        
        if content_type:
            queryset = queryset.filter(content_type=content_type)
        if category:
            queryset = queryset.filter(category=category)
        if status:
            queryset = queryset.filter(status=status)
        if keyword:
            from django.db import models
            queryset = queryset.filter(
                models.Q(title__icontains=keyword) |
                models.Q(keywords__icontains=keyword) |
                models.Q(summary__icontains=keyword)
            )
        
        # 构建返回数据
        knowledge_list = []
        for item in queryset:
            knowledge_list.append({
                'id': item.knowledge_id,
                'title': item.title,
                'type': item.content_type,
                'category': item.category,
                'status': item.status,
                'viewCount': item.view_count,
                'uploader': item.uploader,
                'uploadDate': item.upload_date.strftime('%Y-%m-%d'),
                'summary': item.summary,
                'fileExtension': item.get_file_extension(),
                'fileSize': item.get_file_size_display(),
                'hasFile': bool(item.file_path and item.file_exists())
            })
        
        return JsonResponse({
            'status': 'success',
            'data': knowledge_list
        })
        
    except Exception as e:
        return JsonResponse({
            'status': 'error',
            'message': f'获取知识库列表失败: {str(e)}'
        }, status=400)

@csrf_exempt
@require_http_methods(["POST"])
def upload_knowledge(request):
    """上传知识文件"""
    try:
        # 获取表单数据
        title = request.POST.get('title')
        content_type = request.POST.get('content_type')
        category = request.POST.get('category')
        summary = request.POST.get('summary')
        keywords = request.POST.get('keywords', '')
        uploader = request.POST.get('uploader')
        content = request.POST.get('content', '')
        
        # 获取上传的文件
        uploaded_file = request.FILES.get('file')
        
        # 验证必填字段
        missing_fields = []
        if not title: missing_fields.append('标题')
        if not content_type: missing_fields.append('内容类型')
        if not category: missing_fields.append('分类')
        if not summary: missing_fields.append('内容摘要')
        if not uploader: missing_fields.append('上传人')
        
        if missing_fields:
            print(f"上传失败，缺少字段: {missing_fields}")
            return JsonResponse({
                'status': 'error',
                'message': f'请填写所有必填字段: {", ".join(missing_fields)}'
            }, status=400)
        
        # 保存文件到知识库目录
        file_path = ""
        file_name = ""
        file_size = 0
        
        if uploaded_file:
            # 生成基于日期的文件名
            unique_filename = generate_date_based_filename(uploaded_file.name)
            file_path = unique_filename
            file_name = uploaded_file.name
            file_size = uploaded_file.size
            
            # 保存文件
            absolute_file_path = os.path.join(KNOWLEDGE_FILES_DIR, unique_filename)
            try:
                with open(absolute_file_path, 'wb+') as destination:
                    for chunk in uploaded_file.chunks():
                        destination.write(chunk)
                
                # 验证文件是否保存成功
                if not os.path.exists(absolute_file_path):
                    return JsonResponse({
                        'status': 'error',
                        'message': '文件保存失败'
                    }, status=400)
                    
            except Exception as e:
                return JsonResponse({
                    'status': 'error',
                    'message': f'文件保存失败: {str(e)}'
                }, status=400)
        
        # 创建知识库记录
        knowledge = KnowledgeBase.objects.create(
            title=title,
            content_type=content_type,
            category=category,
            summary=summary,
            keywords=keywords,
            uploader=uploader,
            file_path=file_path,
            file_name=file_name,
            file_size=file_size
        )
        
        # 创建详情记录
        KnowledgeDetail.objects.create(
            knowledge=knowledge,
            title=title,
            summary=summary,
            content=content,
            attachment_path=file_path,
            uploader=uploader
        )
        
        return JsonResponse({
            'status': 'success',
            'message': '上传成功',
            'data': {
                'id': knowledge.knowledge_id,
                'title': knowledge.title
            }
        })
        
    except Exception as e:
        return JsonResponse({
            'status': 'error',
            'message': f'上传失败: {str(e)}'
        }, status=400)

@csrf_exempt
@require_http_methods(["GET"])
def get_knowledge_detail(request, knowledge_id):
    """获取知识详情"""
    try:
        knowledge = KnowledgeBase.objects.get(knowledge_id=knowledge_id)
        
        # 增加浏览次数
        knowledge.view_count += 1
        knowledge.save(update_fields=['view_count'])
        
        # 获取详情信息
        detail = None
        try:
            detail = knowledge.detail
            detail.view_count += 1
            detail.save(update_fields=['view_count'])
        except KnowledgeDetail.DoesNotExist:
            pass
        
        # 构建返回数据
        data = {
            'id': knowledge.knowledge_id,
            'title': knowledge.title,
            'type': knowledge.content_type,
            'category': knowledge.category,
            'status': knowledge.status,
            'viewCount': knowledge.view_count,
            'uploader': knowledge.uploader,
            'uploadDate': knowledge.upload_date.strftime('%Y-%m-%d %H:%M'),
            'keywords': knowledge.keywords,
            'summary': knowledge.summary,
            'content': detail.content if detail else '',
            'fileUrl': f'/knowledge_files/{knowledge.file_path}' if knowledge.file_path else '',
            'filePath': knowledge.file_path,  # 添加文件路径用于下载
            'fileName': knowledge.file_name,
            'fileSize': knowledge.get_file_size_display(),
            'fileExtension': knowledge.get_file_extension()
        }
        
        return JsonResponse({
            'status': 'success',
            'data': data
        })
        
    except KnowledgeBase.DoesNotExist:
        return JsonResponse({
            'status': 'error',
            'message': '知识内容不存在'
        }, status=404)
    except Exception as e:
        return JsonResponse({
            'status': 'error',
            'message': f'获取详情失败: {str(e)}'
        }, status=400)

@csrf_exempt
@require_http_methods(["GET"])
def download_file(request, knowledge_id):
    """下载文件"""
    try:
        knowledge = KnowledgeBase.objects.get(knowledge_id=knowledge_id)
        
        if not knowledge.file_path:
            raise Http404("文件不存在")
        
        # 获取文件绝对路径
        absolute_path = knowledge.get_absolute_file_path()
        if not os.path.exists(absolute_path):
            raise Http404("文件不存在")
        
        # 获取文件信息
        file_name = knowledge.file_name or os.path.basename(absolute_path)
        mime_type, _ = mimetypes.guess_type(absolute_path)
        
        # 读取文件内容并提供下载
        try:
            with open(absolute_path, 'rb') as f:
                file_content = f.read()
                
                # 设置响应内容类型
                response = HttpResponse(file_content, content_type=mime_type or 'application/octet-stream')
                
                # 设置文件下载头，支持中文文件名
                try:
                    # 尝试对文件名进行URL编码以支持中文
                    encoded_filename = urllib.parse.quote(file_name.encode('utf-8'))
                    response['Content-Disposition'] = f'attachment; filename*=UTF-8\'\'{encoded_filename}'
                except:
                    # 如果编码失败，使用ASCII文件名
                    safe_filename = file_name.encode('ascii', 'ignore').decode('ascii')
                    response['Content-Disposition'] = f'attachment; filename="{safe_filename}"'
                
                response['Content-Length'] = len(file_content)
                response['Cache-Control'] = 'no-cache'
                
                return response
                
        except IOError as e:
            raise Http404(f"文件读取失败: {str(e)}")
        except Exception as e:
            raise Http404(f"下载处理失败: {str(e)}")
            
    except KnowledgeBase.DoesNotExist:
        raise Http404("知识内容不存在")
    except Exception as e:
        raise Http404(f"下载失败: {str(e)}")

@csrf_exempt
@require_http_methods(["DELETE"])
def delete_knowledge(request, knowledge_id):
    """删除知识"""
    try:
        knowledge = KnowledgeBase.objects.get(knowledge_id=knowledge_id)
        
        # 删除文件
        if knowledge.file_path:
            absolute_path = knowledge.get_absolute_file_path()
            if os.path.exists(absolute_path):
                os.remove(absolute_path)
        
        # 删除记录
        knowledge.delete()
        
        return JsonResponse({
            'status': 'success',
            'message': '删除成功'
        })
        
    except KnowledgeBase.DoesNotExist:
        return JsonResponse({
            'status': 'error',
            'message': '知识内容不存在'
        }, status=404)
    except Exception as e:
        return JsonResponse({
            'status': 'error',
            'message': f'删除失败: {str(e)}'
        }, status=400)

@csrf_exempt
@require_http_methods(["GET"])
def get_knowledge_statistics(request):
    """获取知识库统计信息"""
    try:
        # 使用更安全的查询方式
        total_count = KnowledgeBase.objects.count()
        standard_count = KnowledgeBase.objects.filter(content_type='标准').count()
        knowledge_count = KnowledgeBase.objects.filter(content_type='知识').count()
        active_count = KnowledgeBase.objects.filter(status='在用').count()
        
        stats = {
            'total_count': total_count,
            'standard_count': standard_count,
            'knowledge_count': knowledge_count,
            'active_count': active_count,
            'categories': []
        }
        
        # 统计各分类数量
        try:
            categories = KnowledgeBase.objects.values_list('category', flat=True).distinct()
            for category in categories:
                if category:  # 确保分类不为空
                    count = KnowledgeBase.objects.filter(category=category).count()
                    stats['categories'].append({
                        'name': category,
                        'count': count
                    })
        except Exception as cat_error:
            # 如果分类统计失败，至少返回基础统计
            print(f"分类统计失败: {cat_error}")
        
        return JsonResponse({
            'status': 'success',
            'data': stats
        })
        
    except Exception as e:
        return JsonResponse({
            'status': 'error',
            'message': f'获取统计信息失败: {str(e)}'
        }, status=400)